import { ref } from 'vue'
import type { ProjectData } from "@/pages/projectList/types"
import type { ProjectListParams } from "@/api/projectList/types"
import { projectList } from "@/api/projectList/index"
function useViewModel() {
	//开启了下拉
	let triggered = ref<boolean>(false)

	//模拟的列表
	let listData = ref<ProjectData[]>([])
	//总页数
	let totalPages = ref<number>()
	//请求参数
	let params = ref<ProjectListParams>({
		projectName: '',
		createDateSearch: '',
		enterpriseId: '',
		deptId: '',
		intentionLevel: '',
		pageSize: 10,
		pageNum: 1
	})


	//获取列表数据
	let getList = (type : 'reload' | 'loadMore') => {
		for(let k in params.value){
			if(!params.value[k as keyof typeof params.value]){
				delete params.value[k as keyof typeof params.value]
			}
		}
		if(type == 'reload'){
				params.value.pageSize = 10
				params.value.pageNum = 1
		}
		projectList(params.value).then((res: any) => {
			let { rows = [], total } = res
			totalPages.value = Math.ceil(total / params.value.pageSize!) as number
			if (type == 'reload') {
				//刷新
				listData.value = rows
			} else {
				//加载下一页
				listData.value = [...listData.value, ...rows]
			}
		}).finally(() => {
			setTimeout(() => {
				triggered.value = false
			}, 1200)

			setTimeout(() => {
				uni.hideLoading()
			}, 500)
		})
	}

	//触底加载下一页
	let loadMore = () : void => {
		params.value.pageNum!++
		if(!(params.value.pageNum! > totalPages.value!)){
			uni.showLoading({
				title: '',
				mask: true
			})
			getList('loadMore')
		}
		
	}

	//下拉刷新
	let refresherrefresh = () : void => {
		triggered.value = true
		getList('reload')
	}

	return { params, getList, listData, loadMore, refresherrefresh, triggered }
}

export default useViewModel